package com.example.permission.controller;

import com.example.permission.entity.User;
import com.example.permission.entity.UserQuery;
import com.example.permission.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    // 任务一：跳转到用户角色查询页面
    @GetMapping("/user/role")
    public String toUserRolePage() {
        return "user-role"; // 对应templates/user-role.html
    }

    // 任务一：处理用户角色查询请求
    @PostMapping("/user/queryWithRoles")
    public String queryUserWithRoles(@RequestParam String username, Model model) {
        // 调用service查询数据
        User user = userService.getUserWithRolesByUsername(username);
        // 将结果存入model，传递到页面
        model.addAttribute("user", user);
        return "user-role"; // 回到查询页面展示结果
    }

    // 任务三：跳转到用户综合查询页面（默认查询第一页）
    @GetMapping("/user/comprehensive")
    public String toUserComprehensivePage(Model model, UserQuery query) {
        // 首次访问时页码默认为1
        if (query.getPageNum() == null) {
            query.setPageNum(1);
        }

        // 查询用户列表和总数
        List<User> userList = userService.getUsersWithRolesAndMenus(query);
        int total = userService.getUserCount(query);
        // 计算总页数（避免0除错误）
        int totalPages = total > 0 ? (total + query.getPageSize() - 1) / query.getPageSize() : 1;

        // 存入model（确保参数正确传递到页面）
        model.addAttribute("userList", userList);
        model.addAttribute("query", query);  // 回显查询条件和当前页码
        model.addAttribute("total", total);
        model.addAttribute("totalPages", totalPages);  // 总页数必须传递

        return "user-comprehensive";
    }
}